package com.leyou.cart.service;

import com.leyou.cart.client.GoodsClient;
import com.leyou.cart.interceptor.LoginInterceptor;
import com.leyou.cart.pojo.Cart;
import com.leyou.common.pojo.UserInfo;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.pojo.Sku;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private GoodsClient goodsClient;

    private static final String KEY_PREFIX = "user_cart";

    public void addCart(Cart cart) {
        //查询用户信息,从拦截器获取
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        //查询购物车记录，stringredis,可读性强，下面object本质就是string
        BoundHashOperations<String, Object, Object> hashOps = this.stringRedisTemplate.boundHashOps(KEY_PREFIX + userInfo.getId());

        String key = cart.getSkuId().toString();
        Integer num = cart.getNum();
        //判断当前商品是否在购物车当中
        if (hashOps.hasKey(key)){
            //在，则修改数量
            //redis的hash模型，得到的是json字符串，需要反序列化为cart对象，覆盖原来的cart
            String jsonCart = hashOps.get(key).toString();
             cart = JsonUtils.parse(jsonCart,Cart.class);
             //设置数量
             cart.setNum(cart.getNum()+num);

        }else {
            //不在，则新增购物车
            cart.setUserId(userInfo.getId());
            //原来cart只携带了skuid和num，需要调用item服务接口，拿到其他数据
            Sku sku = this.goodsClient.querySkuBySkuId(cart.getSkuId());
            cart.setTitle(sku.getTitle());
            cart.setPrice(sku.getPrice());
            cart.setOwnSpec(sku.getOwnSpec());
            //判断图片是否为空，否则以逗号分割为String集合，取第一张图片
            cart.setImage(StringUtils.isBlank(sku.getImages()) ? "" : StringUtils.split(sku.getImages(),",")[0]);
        }
        //重新将修改后的cart序列化保存到redis
        hashOps.put(cart.getSkuId().toString(),JsonUtils.serialize(cart));


    }

    public List<Cart> queryCartList() {
        //根据拦截器，获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        //判断用户是否有购物车记录
        if (!this.stringRedisTemplate.hasKey(KEY_PREFIX+userInfo.getId())){
            return null;
        }
        //通过用户信息，在redis中获取购物车信息
        BoundHashOperations<String, Object, Object> hashOps = this.stringRedisTemplate.boundHashOps(KEY_PREFIX + userInfo.getId());
        //获取购物车Map集合里面的Cart值集合
        List<Object> cartsJson = hashOps.values();
        //如果购物车集合为空，则返回null
        if (CollectionUtils.isEmpty(cartsJson)){
            return null;
        }
        //遍历list集合里面的每件商品，并且反序列化为字符串，组成只有cart对象 ，list集合，List<Cart>
        return cartsJson.stream().map(cartJson -> JsonUtils.parse(cartJson.toString(), Cart.class)).collect(Collectors.toList());

    }

    /**
     * 修改商品数量
     * @param cart
     * @return
     */
    public void updateNum(Cart cart) {
        //根据拦截器，获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        //判断用户是否有购物车记录
        if (!this.stringRedisTemplate.hasKey(KEY_PREFIX+userInfo.getId())){
            return ;
        }
        //通过用户信息，在redis中获取购物车信息
        BoundHashOperations<String, Object, Object> hashOps = this.stringRedisTemplate.boundHashOps(KEY_PREFIX + userInfo.getId());
        //将前端带过来的num保存一下
        Integer num = cart.getNum();
        //通过skuId，获取cart对象
        String cartJson = hashOps.get(cart.getSkuId().toString()).toString();
        //解析cart对象，并且覆盖原来的
        cart = JsonUtils.parse(cartJson, Cart.class);
        //将修改的数量，设置给cart
        cart.setNum(num);
        //重新设置给redis保存
        hashOps.put(cart.getSkuId().toString(),JsonUtils.serialize(cart));
    }

    public void deleteCart(String skuId) {
        //根据拦截器，获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        //判断用户是否有购物车记录
        if (!this.stringRedisTemplate.hasKey(KEY_PREFIX+userInfo.getId())){
            return ;
        }
        //通过用户信息，在redis中获取购物车信息
        BoundHashOperations<String, Object, Object> hashOps = this.stringRedisTemplate.boundHashOps(KEY_PREFIX + userInfo.getId());

        hashOps.delete(skuId);

    }
}
